package com.central.modules.sys.controller;

import cn.hutool.core.lang.tree.Tree;
import com.central.common.utils.Result;
import com.central.modules.sys.entity.SysMenuEntity;
import com.central.modules.sys.entity.SysRoleMenuEntity;
import com.central.modules.sys.model.AddSysMenuRequest;
import com.central.modules.sys.service.SysMenuService;
import com.central.modules.sys.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单管理
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys_menu")
public class SysMenuController {

    private final SysMenuService sysMenuService;
    private final SysRoleMenuService roleMenuService;

    //查询所有的 列表
    @GetMapping("/all")
    public Result<List<SysMenuEntity>> findAll() {
        List<SysMenuEntity> list = sysMenuService.findAll();
        return Result.succeed(list);
    }

    /**
     * 返回树形菜单集合
     *
     * @param parentId 父节点ID
     * @param menuName 菜单名称
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public Result<List<Tree<Long>>> getTree(Long parentId, String menuName, String type) {
        return Result.succeed(sysMenuService.treeMenu(parentId, menuName, type));
    }


    @PostMapping("/add")
    public Result<Map<String, Object>> add(@RequestBody AddSysMenuRequest request) {
        sysMenuService.addMenu(request);
        return Result.succeed(null);
    }

    @PutMapping("/update")
    public Result<Map<String, Object>> update(@RequestBody AddSysMenuRequest request) {
        sysMenuService.updateMenu(request.getId(), request);
        return Result.succeed(null);
    }

    @DeleteMapping("/del")
    public Result<Map<String, Object>> del(@RequestParam Long id) {
        sysMenuService.deleteMenu(id);
        roleMenuService.cleanByMenuId(id);
        return Result.succeed(null);
    }

    @GetMapping("/find_ids_by_roleId/{roleId}")
    public Result<List<Long>> findIdsByRoleId(@PathVariable Long roleId) {
        return Result.succeed(roleMenuService.listAllByRoleId(roleId).stream().map(SysRoleMenuEntity::getMenuId).collect(Collectors.toList()));
    }

}
